package com.bardsoftware.foronuvolo.client;

import javax.servlet.RequestDispatcher;


import com.bardsoftware.foronuvolo.server.RssListener;
import com.google.gdata.util.common.base.Pair;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dev.shell.BrowserChannel;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;


public class RssModuleUI implements EntryPoint {
	private Button addFeedButton = new Button("Add");
	private Button clearButton = new Button("Clear");
	private TextBox feedURL = new TextBox();
	private HorizontalPanel addPanel = new HorizontalPanel();
	private AddFeedServiceAsync feedService = GWT.create(AddFeedService.class);
	
	@Override
	public void onModuleLoad() {
		String url = Document.get().getURL();
		int pos = url.indexOf("=");
		final String userId = url.substring(pos+1);	
		
		
		addPanel.add(feedURL);
		addPanel.add(addFeedButton);
		addPanel.add(clearButton);			
		
		
		clearButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				feedURL.setText("");				
			}
		});
		
		addFeedButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {				
				String feedUrl = feedURL.getText();				
				if(feedUrl == "") {
					Window.alert("If you want to add feed you should enter URL of it");					
				}
				else {					
					feedService.addFeed(feedUrl, userId, new AsyncCallback<String>() {						
						@Override
						public void onSuccess(String result) {						
							Window.alert("Thank you! You feed successfully added. \n You can add other feeds or back to main page.");
						}
						
						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Server error. Your feed hasn't be added. Try again later.");							
						}
					});
					feedURL.setText("");
				}
			}
		});		
		RootPanel.get("add_panel").add(addPanel);
	}

}
